let express = require('express');
let router = express.Router();

/**
 * 进入考试 by p 2018-06-19
 *
 * 根据考试编号、房间密码获取考试信息
 *
 */
router.post('/exam', function (req, res, next) {
    let params = req.body;

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "房间密码不能为空！"});
        return;
    }

    req.app.db.query("select * from exam where id = ? and password = ?", [params.examId, params.password], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "考试信息或密码错误！"});
            return;
        }

        if (results[0].isActived === 0) {
            res.json({"success": false, "message": "考试未开启或已关闭！"});
            return;
        }

        res.json({"success": true, "data": {"exam": results[0]}});
    });
});

/**
 * 校验考生信息 by p 2018-06-19
 *
 * 根据考试编号、学生身份证信息校验考生是否参加过当前考生
 *
 */
router.post('/isLogged', function (req, res, next) {
    let params = req.body;

    req.app.db.query("select * from exam where id = ?", [params.examId],  function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "考试信息错误！"});
            return;
        }

        let exam = results[0];

        req.app.db.query("select * from score where examId = ? and idCard = ?", [exam.id, params.idCard], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length !== 0) {
                res.json({"success": false, "message": "已参加过考试，不能重复考试！"});
                return;
            }

            if (global["students"][params.examId] === undefined) {
                global["students"][params.examId] = [];
            }

            if (global["students"][params.examId][params.idCard] !== undefined) {
                let distanceSecond = (new Date() - global["students"][params.examId][params.idCard].startTime) / (1000 * 60);
                if (distanceSecond < exam.totalTimes) {
                    res.json({"success": false, "message": "此证件号正在参加考试，不能重复考试！"});
                    return;
                }
            }

            global["students"][params.examId][params.idCard] = {"startTime": new Date()};
            res.json({"success": true, "message": "可以考试！"});
        });
    });
});

/**
 * 获取试卷 by p 2018-06-15
 *
 * 根据考试编号获取一张随机考卷
 *
 */
router.get('/rand', function (req, res, next) {
    let params = req.query;

    req.app.db.query("select * from exam where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "考试信息错误！"});
            return;
        }

        let exam = results[0];
        req.app.db.query("select * from paper where examId = ? order by Rand() LIMIT 1", [params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "试卷信息错误！"});
                return;
            }

            let paper = results[0];
            req.app.db.query("select * from question where FIND_IN_SET(id, ('" + paper.questionIds + "')) order by types, id", [], function (err, results, fields) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                if (results.length === 0) {
                    res.json({"success": false, "message": "试卷信息错误！"});
                    return;
                }

                res.json({
                    "success": true,
                    "data": {"exam": exam, "paper": paper, "questions": results},
                    "totalCount": results.length
                });
            });
        });
    });
});


/**
 * 保存成绩数据 by p 2018-06-15
 *
 * 只能新增，不能修改
 */
router.post('/', function (req, res, next) {
    let params = req.body;

    var score = 0;

    if (params.examId === undefined || params.examId === "") {
        res.json({"success": false, "message": "考试信息不正确！"});
        return;
    }

    if (params.paperId === undefined || params.paperId === "") {
        res.json({"success": false, "message": "试卷信息不正确！"});
        return;
    }

    if (params.score > 0) {
        score = params.score;
    }

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "姓名不能为空！"});
        return;
    }

    if (params.idCard === undefined || params.idCard === "") {
        res.json({"success": false, "message": "身份证不能为空！"});
        return;
    }

    req.app.db.query("select * from score where examId = ? and idCard = ?", [params.examId, params.idCard], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length !== 0) {
            res.json({"success": false, "message": "已参加过考试，不能重复考试！"});
            return;
        }

        req.app.db.query("insert into score(examId, paperId, answers, score, name, idCard) values(?, ?, ?, ?, ?, ?)", [params.examId, params.paperId, JSON.stringify(params.answers), score, params.name, params.idCard], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (global["students"][params.examId] === undefined) {
                global["students"][params.examId] = [];
            }

            if (global["students"][params.examId][params.idCard] !== undefined) {
                global["students"][params.examId][params.idCard] = undefined;
            }

            res.json({"success": true, "message": global.postMsg});
        });
    });
});

module.exports = router;